#include "util.hpp"

volatile bool quit=false;
void Usage(std::string proc)
{
    std::cerr << "Usage:\n\t" << proc << " ip port" << std::endl;
    std::cerr << "exmaple:\n\t" << proc << " 127.0.0.11 8080 \n"
              << std::endl;
}

//./clientTcp serverIp serverPort
int main(int argc, const char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t serverPort = atoi(argv[2]);
    std::string serverIp = argv[1];
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock<0)
    {
        std::cerr<<"socket: "<<strerror(errno)<<std::endl;
        exit(SOCKET_ERR);
    }
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(serverPort);
    inet_aton(serverIp.c_str(),&server.sin_addr);
    if(connect(sock,(struct sockaddr *)&server,sizeof(server))<0)
    {
        std::cerr << "connect: " << strerror(errno) << std::endl;
        exit(CONN_ERR);
    }
    std::cout << "info : connect success: " << sock << std::endl;
    std::string message;
    while(!quit)
    {
        message.clear();
        std::cout << "请输入你的消息>>> ";
        getline(std::cin,message);              //std:: ???
        if(strcasecmp(message.c_str(),"quit")==0)
            quit=true;
        ssize_t s=write(sock, message.c_str(),message.size());
        if(s>0)
        {
            message.resize(1024);
            ssize_t s=read(sock,(void*)message.c_str(),message.size());
            if(s>0) message[s]=0;
            std::cout << "Server Echo>>> " << message << std::endl;
        }
        else
        {
            break;
        }
    }
    close(sock);
    return 0;
}